package com.easy.common.util;

import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CaptchaUtil {
    private static final ExpiryMap expiryMap=new ExpiryMap();
    private static final long EXPIRY_TIME=1000*60*8;//验证码过期时间
    //获取验证码
    public static Map getCaptcha() {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = cn.hutool.captcha.CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        System.out.println("___________________");
        System.out.println(captcha);
        //图片
        String imagebase64 =Base64.encode(captcha.getImageBytes());
        System.out.println(imagebase64);
        //验证码的遍号
        String code = captcha.getCode();
        System.out.println(code);
        String key= UUID.randomUUID().toString();
        Map map=new HashMap();
        map.put("key",key);
        map.put("base","data:image/png;base64,"+imagebase64);
        expiryMap.put(key,code,EXPIRY_TIME);//添加数据


        return map;
    }

//    public static void main(String[] args) {
//        getCaptcha();
//        ExpiryMap expiryMap=new ExpiryMap();//创建一个带过期时间的map
//        expiryMap.put("1",1);
//        expiryMap.put("2",2,8000);//5秒
//        try {
//            Thread.sleep(7000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        System.out.println(expiryMap.get("1"));
//        System.out.println(expiryMap.get("2"));
//    }

    //验证验证码
    public static boolean checkCaptcha(String key,String code) {
        String captchaCode= (String) expiryMap.get(key);
        return code.equalsIgnoreCase(captchaCode);//比较并且忽略大小写
    }
}



















